package com.bjsxt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**双向通信：任何一方都可以是发送端，任何一方都可以是接收端*/
/*存在缺陷，只有在服务端先发送信息才可以接收客户端发来的信息*/
public class TwoWayServerSocket {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        BufferedReader br = null;
        Scanner scanner = null;//向客户端发送信息时用
        PrintWriter pw = null;//发送给客户端
        try{
            serverSocket = new ServerSocket(8888);

            System.out.println("启动服务端，监听8888");
            socket =serverSocket.accept();
            //创建从客读取信息
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //创建键盘输入对象
            scanner = new Scanner(System.in);
            //创建向客户端发送消息的输出流对象
            pw = new PrintWriter(socket.getOutputStream());
           while (true){
               //读取客户端发送的消息
               String str = br.readLine();
               System.out.println("客户端说："+str);
               //向客户端发送消息
               String serverInput = scanner.nextLine();
               pw.println(serverInput);
               pw.flush();
           }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(scanner != null){
                scanner.close();
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(pw != null){
                pw.close();
            }
        }
    }
}
